package com.claude.mainactivity;

import java.util.ArrayList;

import com.claude.bean.Subject;
import com.claude.sql.SQLManager;
import com.claude.sql.SubjectTableManager;
import com.claude.util.Configure;
import com.special.ResideMenuDemo.MenuActivity;
import com.special.ResideMenuDemo.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class SubjectSelectActivity extends Activity {
	private ListView mListView = null;
	private MyApplication mMyApplication = null;
	private Configure configure = null;
	private ArrayAdapter<Subject> mArrayAdapter = null;
	private ArrayList<Subject> mArrayList = null;
	private OnItemClickListener mOnItemClickListener = null;
	private int mItemResouce = R.layout.my_list_item;
	private SQLManager mSQLManager = null;
	private SubjectTableManager mSubjectTableManager = null;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_subject);

		mMyApplication = (MyApplication) getApplication();
		configure = Configure.getInstance();

		mArrayList = mMyApplication.getSubjects();
		mArrayAdapter = new ArrayAdapter<Subject>(SubjectSelectActivity.this,
				mItemResouce, mArrayList);
		if(mArrayList == null){
			gotoBack();
		}
		this.initView();
	}

	public void onResume() {
		mSQLManager = new SQLManager(this);
		mSubjectTableManager = new SubjectTableManager(
				mSQLManager.getWritableDatabase());
		super.onResume();
	}

	private void initView() {
		mListView = (ListView) findViewById(R.id.listview);
		mListView.setAdapter(mArrayAdapter);
		mOnItemClickListener = new MyOnItemClickListener();
		mListView.setOnItemClickListener(mOnItemClickListener);
	}

	class MyOnItemClickListener implements OnItemClickListener {
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			Subject subject = mArrayList.get(arg2);
			mMyApplication.setCurSubject(subject);
			mSubjectTableManager.insert(subject.getSubjectNumber(), subject
					.getName(), mMyApplication.getUser().getTeacherNumber());
			mSQLManager.close();
			gotoClassSelect();
		}
	}

	private void gotoClassSelect() {
		Intent intent = new Intent();
		intent.setClass(SubjectSelectActivity.this, ClassSelectActivity.class);
		SubjectSelectActivity.this.startActivity(intent);
	}
	
	private void gotoBack(){
		Intent intent = new Intent();
		intent.setClass(SubjectSelectActivity.this, MenuActivity.class);
		SubjectSelectActivity.this.startActivity(intent);
	}
}
